﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using PaperRenderingInterfaces;
using DeepZoomPivotConstructor.PivotLib;
using PaperPluginUtilities;
using System.IO;

namespace DZEROPhysicsResultsPages
{
    /// <summary>
    /// A wrapper around another dude that does the real scanning. We just add some stuff
    /// that is unique to DZERO.
    /// </summary>
    [Export(typeof(IPaperRender))]
    [PaperRender("DZERONotePage")]
    public class ScanDZERONotePage : IPaperRender
    {
        [Import]
        IPaperRenderEngine MyPaperRenderEngine;

        /// <summary>
        /// Grab the images and render the note link! :-)
        /// </summary>
        /// <param name="renderAddress"></param>
        /// <returns></returns>
        public IEnumerable<PivotImage> Render(string renderAddress)
        {
            string[] allUris = renderAddress.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string paperAddress = renderAddress;
            if (!paperAddress.EndsWith("/"))
            {
                paperAddress += "/";
            }
            paperAddress += allUris.Last() + ".pdf";
            Uri paperUri = new Uri(paperAddress);

            var images = MyPaperRenderEngine.Render("HTMLSimpleTableCells", renderAddress)
                .Apply(i => i.Name = SetNameByURL(i));

            return images;
        }

        /// <summary>
        /// Get a better name than "jpeg" or whatever for the image.
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        private string SetNameByURL(PivotImage i)
        {
            var urls = (from f in i.GetMetadata<PivotMetadataURL>("Graphics Files") select f.LinkUri).FirstOrDefault();
            if (urls != null)
            {
                string splitLast = urls.OriginalString.Split('/').Last();
                return Path.GetFileNameWithoutExtension(splitLast);
            }
            return i.Name;
        }
    }
}
